import { useMorghulisRequest } from '../hooks/request';
import type { MorOption } from '../types/io.types';
import type { MorghulisOptions, MorghulisChannel, MorghulisChannels } from '../types/channel.types';
import { reactive, ref, watch } from 'vue';
import { useMorghulisAuthorize } from '../hooks/authorize';

// WebSocket管理接口
export interface MorghulisSockets {
  status: ReturnType<typeof ref<string>>;
  open: () => void;
  channels: MorghulisChannels;
}

// 加载WebSocket连接
export function loadMorghulisSockets(baseURL: string): MorghulisSockets {
  const { $client } = useMorghulisAuthorize();
  const channels = reactive<MorghulisChannels>({});
  const URL = `${baseURL}${$client}/`;
  let status = ref('DISCONNECTED');
  
  // 模拟WebSocket连接
  const data = ref('');
  const open = () => {
    status.value = 'CONNECTED';
    console.log('WebSocket连接已打开');
  };
  
  // 监听数据变化
  watch(data, () => {
    if (!data.value) return;
    try {
      let { payload, handler, status: eventStatus } = JSON.parse(data.value);
      const channel: MorghulisChannel = channels[handler];
      const fun = channel[eventStatus as 'start' | 'stop' | 'proceed'];
      fun && fun(payload);
    } catch (error) {
      console.error('处理WebSocket数据时出错:', error);
    }
  }, { deep: true });

  return {
    open,
    status,
    channels
  };
}

// 增强的通信通道实现
export const $channel = (options: MorOption & MorghulisOptions = {}) => {
  const baseURL = options.baseURL || '/api/';
  const timeout = options.timeout || 30000;
  const headers = options.headers || {};
  
  // 获取请求实例
  const { getRequest } = useMorghulisRequest(baseURL);
  const http = getRequest();
  
  // 初始化WebSocket
  const sockets = loadMorghulisSockets(baseURL);
  
  return {
    // 发送消息
    send: (event: string, data: any) => {
      console.log(`发送消息: ${event}`, data);
      // 使用http实例发送请求
      return http.post(event, data);
    },
    
    // 接收消息
    on: (event: string, callback: Function) => {
      console.log(`监听事件: ${event}`);
      // 实际监听逻辑
      return () => {
        console.log(`取消监听: ${event}`);
        // 取消监听逻辑
      };
    },
    
    // 关闭通道
    close: () => {
      console.log('关闭通道');
      // 实际关闭逻辑
    },
    
    // 暴露http实例和WebSocket
    http,
    sockets
  };
};